from django.db import models
from django.utils import timezone
import uuid
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in

# 用户配置文件模型
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name='手机号')
    last_login_time = models.DateTimeField(blank=True, null=True, verbose_name='最后登录时间')
    
    def __str__(self):
        return f'{self.user.username}的个人资料'
    
    class Meta:
        verbose_name = '用户配置文件'
        verbose_name_plural = '用户配置文件'

# 信号处理：当用户创建时自动创建用户配置文件
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

# 信号处理：当用户更新时同步更新用户配置文件
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

class Server(models.Model):
    """服务器模型"""
    ip = models.CharField(max_length=20, verbose_name='IP地址')
    ssh_port = models.IntegerField(default=22, verbose_name='SSH端口')
    ssh_password = models.CharField(max_length=100, verbose_name='SSH密码')
    remark = models.CharField(max_length=200, blank=True, null=True, verbose_name='备注')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '服务器'
        verbose_name_plural = '服务器列表'
        ordering = ['-created_time']
    
    def __str__(self):
        return f"{self.ip}:{self.ssh_port}"

class CDNDomain(models.Model):
    """CDN域名模型"""
    DOMAIN_VENDOR_CHOICES = (
        ('aliyun', '阿里云'),
        ('tencent', '腾讯云'),
        ('wangsu', '网宿科技'),
        ('qiniu', '七牛云'),
        ('other', '其他'),
    )
    domain = models.CharField(max_length=100, verbose_name='CDN域名')
    vendor = models.CharField(max_length=20, choices=DOMAIN_VENDOR_CHOICES, verbose_name='厂商')
    project = models.CharField(max_length=100, verbose_name='归属项目')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = 'CDN域名'
        verbose_name_plural = 'CDN域名列表'
        ordering = ['-created_time']
        unique_together = ('domain',)
    
    def __str__(self):
        return f"{self.domain}({self.get_vendor_display()})"

class RequestUrl(models.Model):
    """请求地址模型"""
    url = models.CharField(max_length=500, verbose_name='请求地址')
    cdn_domain = models.ForeignKey(CDNDomain, on_delete=models.CASCADE, verbose_name='关联CDN域名')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    class Meta:
        verbose_name = '请求地址'
        verbose_name_plural = '请求地址列表'
        ordering = ['-created_time']
    
    def __str__(self):
        return f"{self.cdn_domain.domain}{self.url}"

class AutoTask(models.Model):
    """自动任务模型"""
    TASK_TYPE_CHOICES = (
        ('minute', '分钟'),
        ('hour', '小时'),
        ('day', '天'),
    )
    name = models.CharField(max_length=100, verbose_name='任务名称')
    description = models.TextField(blank=True, null=True, verbose_name='任务描述')
    servers = models.ManyToManyField(Server, verbose_name='关联服务器')
    request_urls = models.ManyToManyField(RequestUrl, verbose_name='请求地址列表')
    task_type = models.CharField(max_length=20, choices=TASK_TYPE_CHOICES, verbose_name='任务类型')
    interval = models.IntegerField(verbose_name='执行间隔')
    is_active = models.BooleanField(default=True, verbose_name='是否激活')
    last_executed_time = models.DateTimeField(blank=True, null=True, verbose_name='上次执行时间')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '自动任务'
        verbose_name_plural = '自动任务列表'
        ordering = ['-created_time']
    
    def __str__(self):
        return self.name

class TaskExecutionResult(models.Model):
    """任务执行结果模型"""
    task = models.ForeignKey(AutoTask, on_delete=models.CASCADE, verbose_name='关联任务')
    execution_time = models.DateTimeField(auto_now_add=True, verbose_name='执行时间')
    success = models.BooleanField(verbose_name='是否成功')
    success_count = models.IntegerField(default=0, verbose_name='成功数量')
    failed_count = models.IntegerField(default=0, verbose_name='失败数量')
    failed_urls = models.TextField(blank=True, null=True, verbose_name='失败的URL')
    
    class Meta:
        verbose_name = '任务执行结果'
        verbose_name_plural = '任务执行结果列表'
        ordering = ['-execution_time']
    
    def __str__(self):
        status = '成功' if self.success else '失败'
        return f"{self.task.name} - {status} - {self.execution_time}"

class ManualPreheat(models.Model):
    """手动预热模型"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100, blank=True, null=True, verbose_name='任务名称')
    description = models.TextField(blank=True, null=True, verbose_name='任务描述')
    servers = models.ManyToManyField(Server, verbose_name='选择的服务器')
    request_urls = models.ManyToManyField(RequestUrl, verbose_name='请求地址列表')
    status = models.CharField(max_length=20, default='pending', verbose_name='状态')
    failed_urls = models.TextField(blank=True, null=True, verbose_name='失败的URL')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    completed_time = models.DateTimeField(blank=True, null=True, verbose_name='完成时间')
    
    class Meta:
        verbose_name = '手动预热'
        verbose_name_plural = '手动预热记录'
        ordering = ['-created_time']
    
    def __str__(self):
        return self.name if self.name else f"预热任务 - {self.id}"

# 信号处理：当用户登录时更新最后登录时间
@receiver(user_logged_in)
def update_last_login_time(sender, user, request, **kwargs):
    # 获取或创建用户配置文件
    profile, created = UserProfile.objects.get_or_create(user=user)
    # 更新最后登录时间
    profile.last_login_time = timezone.now()
    profile.save()
